<template>
  <el-card class="page_card">
    <el-form :inline="true" class="form">
      <el-form-item label="学生账户：">
        <el-input v-model="data.queryForm.username" placeholder="请输入学生账户"></el-input>
      </el-form-item>
      <el-form-item label="学生姓名：">
        <el-input v-model="data.queryForm.realname" placeholder="请输入学生姓名"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" color="#626aef" @click="search" 
          :disabled="(!data.queryForm.username&&!data.queryForm.realname)?true:false">搜索</el-button>
        <el-button @click="reset" color="#626aef" plain>重置</el-button>
      </el-form-item>
    </el-form>
    <el-button type="primary" icon="Plus" @click="addUser">添加学生</el-button>
    <el-button type="danger" :disabled="data.selectIdArr.length?false:true" @click="deleteSelectUser">批量删除</el-button>
    <el-table style="margin: 10px 0;" border :data="data.userTableData" @selection-change="selectionChange" max-height="663">
      <el-table-column type="selection" align="center"></el-table-column>
      <el-table-column label="#" align="center" type="index" :width="80"></el-table-column>
      <el-table-column label="学生账户" align="center" prop="username"></el-table-column>
      <el-table-column label="学生姓名" align="center" prop="realname"></el-table-column>
      <el-table-column label="性别" align="center" prop="gender"></el-table-column>
      <el-table-column label="创建时间" align="center" show-overflow-tooltip>
        <template #default="scope">{{ scope.row.createTime?.slice(0,10) }}</template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" show-overflow-tooltip>
        <template #default="scope">{{ scope.row.updateTime?.slice(0,10) }}</template>
      </el-table-column>
      <el-table-column label="状态" align="center" width="160px">
        <template #default="scope">
          <el-switch v-model="scope.row.active" :active-value="1" :inactive-value="0" 
            active-text="启用" inactive-text="停用" @change="changeStatus($event,scope.row)"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200px" align="center">
        <template #="{row}">
          <el-button type="primary" link icon="Edit" @click="updateUser(row)">编辑</el-button>
          <el-popconfirm :title="`确认删除${row.username}吗？`" width="260px" @confirm="deleteUser(row)">
            <template #reference>
              <el-button type="danger" link icon="Delete">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-model:current-page="data.currentPage"
      v-model:page-size="data.pageSize"
      :page-sizes="[10, 20, 30, 40]"
      :background="true"
      layout="->,prev, pager, next, jumper,sizes,total"
      :total="data.total"
      @current-change="currentChange"
      @size-change="sizeChange"
    />
  </el-card>
  <!-- 添加学生、修改学生 -->
  <el-dialog v-model="data.addUserDialog" :title="data.userForm.id?'更新学生':'添加学生'" width="650">
    <el-form :model="data.userForm" :rules="rules" ref="formRef" label-width="130px" style="max-width: 550px">
      <el-form-item label="学生账户" prop="username">
        <el-input v-model="data.userForm.username" placeholder="请输入学生账户" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="学生姓名" prop="realname">
        <el-input v-model="data.userForm.realname" placeholder="请输入学生姓名" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="data.userForm.password" placeholder="请输入用户密码" type="password" show-password autocomplete="new-password"></el-input>
      </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-radio-group v-model="data.userForm.gender">
          <el-radio value="男">男</el-radio>
          <el-radio value="女">女</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="save">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import {ref,onMounted,reactive,nextTick} from 'vue'
import {reqAllUser,reqAddOrUpdateUser,reqRemoveUser,reqRemoveUsers,reqChangeActive,reqAllRole} from '@/api/sys/userApi'
import type {UserResData,Records,User} from '@/api/sys/userType'
import { ElMessage } from 'element-plus'
import useLayOutSettingStore from '@/store/modules/setting'

let settingStore = useLayOutSettingStore() // 模板setting仓库
let formRef = ref<any>() //form组件实例
const data = reactive({
  queryForm:{
    username:'',
    realname:'',
  },
  userTableData:[] as Records,
  currentPage:1,
  pageSize:10,
  total:0,
  addUserDialog:false, //新增对话框
  userForm:{ //新增表单
    userType:'2', 
    username:'', //学生账户
    realname:'', //学生姓名
    password:'',  //密码
    gender:'男', //性别
    roleId:'', //分配角色id
    id:'',
  },
  selectIdArr:[],//批量删除勾选的用户id
  commonRoleId:'', //普通用户 roleid
})

onMounted(() => {
  initUserData()
  getCommonRoleId()
})

// 获取普通用户 roleid
const getCommonRoleId = async () => {
  let res = await reqAllRole()
  if (res.code == 200) {
    data.commonRoleId = res.data.records.find((item:any) => item.roleName == 'common_role').id
  }
}

// 状态 启用/停用
const changeStatus = async(event:number,row:User) => {
  let params = {
    id:row.id,
    active:event,
    version:row.version
  }
  let res = await reqChangeActive(params)
  if(res.code==200){
    ElMessage.success(event==0?'停用成功！':'启用成功！')
    initUserData()
  }else{
    ElMessage.error(res.msg)
  }
}

// 搜索
const search = ()=>{
  initUserData()
}
// 重置
const reset = ()=>{
  settingStore.refsh = !settingStore.refsh
}
// 获取学生列表
const initUserData = async(pager=1)=> {
  data.currentPage = pager
  let params = {
    current:data.currentPage,
    size:data.pageSize,
    userType:'2',
    ...data.queryForm
  }
  let res:UserResData = await reqAllUser(params)
  if(res.code==200){
    data.userTableData = res.data.records
    data.total = res.data.total
  }
}
// 分页器下拉事件
const currentChange = () => {
  initUserData(data.currentPage)
}
const sizeChange = ()=> {
  initUserData()
}
const addUser = ()=> {
  data.addUserDialog = true
  // 清空数据
  Object.assign(data.userForm,{
    userType:'2', 
    username:'', //学生账户
    realname:'', //学生姓名
    password:'',  //密码
    gender:'男', //性别
    roleId:'', //分配角色id
    id:'',
  })
  nextTick(() => {
    // 清除上一次错误提示信息
    formRef.value.clearValidate('username')
    formRef.value.clearValidate('realname')
    formRef.value.clearValidate('password')
  })
}
const updateUser = (row:User)=> {
  data.addUserDialog = true
  Object.assign(data.userForm,row)
  nextTick(() => {
    // 清除上一次错误提示信息
    formRef.value.clearValidate('username')
    formRef.value.clearValidate('realname')
    formRef.value.clearValidate('password')
  })
}
// 新增用户确认按钮
const save = async()=>{
  try{
    await formRef.value.validate()
    data.userForm.roleId = data.commonRoleId
    let res:any = await reqAddOrUpdateUser(data.userForm)
    if(res.code==200){
      data.addUserDialog = false
      ElMessage.success(data.userForm.id?'更新成功！':'添加成功！')
      initUserData()
    }else{
      ElMessage.error(res.msg)
    }
  }catch (error) {}
}
const cancel = ()=>{
  data.addUserDialog = false
}
// @ts-ignore
const validatorUsername = (rule:any,value:any,callBack:any)=>{
  // 用户名至少5位
  if(value.trim().length>=3){
    callBack()
  }else{
    callBack(new Error('学生账户至少3位'))
  }
}
// @ts-ignore
const validatorPassword = (rule:any,value:any,callBack:any)=>{
  // 用户名至少5位
  if(value.trim().length>=6){
    callBack()
  }else{
    callBack(new Error('密码至少6位'))
  }
}
// 表单校验规则对象
const rules = {
  username:[{ required: true, trigger: 'blur',validator:validatorUsername }],
  realname:[{ required: true, trigger: 'blur', message:'请输入学生姓名'}],
  password:[{ required: true, trigger: 'blur',validator:validatorPassword }],
}
// 删除单行用户
const deleteUser = async(row:User)=>{
  let res = await reqRemoveUser((row.id as number),row.version)
  if(res.code==200){
    ElMessage.success('删除成功！')
    initUserData(data.userTableData.length==0?1:data.currentPage)
  }else{
    ElMessage.error('删除失败！')
  }
}
// table复选框勾选事件
const selectionChange = (value:any)=> {
  data.selectIdArr = value
}
// 批量删除
const deleteSelectUser = async()=> {
  let ids = data.selectIdArr.map((item:any) => item.id).join(',')
  let versions = data.selectIdArr.map((item:any) => item.version).join(',')
 let res = await reqRemoveUsers(ids,versions)
 if(res.code==200){
    ElMessage.success('批量删除成功！')
    initUserData(data.userTableData.length==0?1:data.currentPage)
  }else{
    ElMessage.error(res.msg)
  }
} 
</script>

<style scoped lang="scss">

</style>


